package com.lamp.connection;

import java.io.BufferedReader;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.protocol.HTTP;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

import com.lamp.downloadimage.HttpClientFactory;
public class HttpConnection {

	private String json;
	private HttpResponse response;
	private HttpClient client;
	private HttpPost request;
	private BufferedReader in;

	public HttpConnection() {

	}

	private static class FlushedInputStream extends FilterInputStream {
		public FlushedInputStream(InputStream inputStream) {
			super(inputStream);
		}

		@Override
		public long skip(long n) throws IOException {
			long totalBytesSkipped = 0L;
			while (totalBytesSkipped < n) {
				long bytesSkipped = in.skip(n - totalBytesSkipped);
				if (bytesSkipped == 0L) {
					int b = read();
					if (b < 0) {
						break;
					} else {
						bytesSkipped = 1;
					}
				}
				totalBytesSkipped += bytesSkipped;
			}
			return totalBytesSkipped;
		}
	}

	protected Bitmap downloadBitmap(String url) {

		HttpClient client = HttpClientFactory.getThreadSafeClient();
		final HttpGet getRequest = new HttpGet(url);

		try {
			HttpResponse response = client.execute(getRequest);
			final int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode != HttpStatus.SC_OK) {
				Log.w("ImageDownloader", "Error " + statusCode
						+ " while retrieving bitmap from " + url);
				return null;
			}

			final HttpEntity entity = response.getEntity();
			if (entity != null) {
				InputStream inputStream = null;
				try {
					inputStream = entity.getContent();
					// return BitmapFactory.decodeStream(inputStream);
					return BitmapFactory.decodeStream(new FlushedInputStream(
							inputStream));
				} finally {
					if (inputStream != null) {
						inputStream.close();
					}
					entity.consumeContent();
				}
			}
		} catch (IOException e) {
			getRequest.abort();
			Log.w("ImageDownloader", "no connection" + url, e);
		} catch (IllegalStateException e) {
			getRequest.abort();
			Log.w("ImageDownloader", "wrong URL: " + url);
		} catch (Exception e) {
			getRequest.abort();
			Log.w("ImageDownloader", "" + url, e);
		}
		return null;
	}

	protected void requestAbort() {
		request.abort();
	}

	protected String postHtml(String _url, List<NameValuePair> postParameters) {
		json = null;
		response = null;
		client = null;
		request = null;
		in = null;

		client = HttpClientFactory.getThreadSafeClient();
		request = new HttpPost(_url);

		try {
			UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(
					postParameters, HTTP.UTF_8);
			request.setEntity(formEntity);
			response = client.execute(request);
			in = new BufferedReader(new InputStreamReader(response.getEntity()
					.getContent(), HTTP.UTF_8));

			String line = "";
			json = "";
			while ((line = in.readLine()) != null) {

				json += line;
			}

			if (response.getStatusLine().getStatusCode() == 200) {
				return json;
			} else {
				// //Log.println(Log.INFO, AppDefines.NRANGE_TAG,
				// "Response code:" + response);
			}
		} catch (Exception e) {

			Log.d("SocketException", "Catch Excetion");
		} finally {

			if (request != null) {
				try {
					request.abort();
					Log.d("Abort", "Aborted");
					Log.d("STATUS", "" + response.getStatusLine());
				} catch (Exception e) {
					// TODO: handle exception
				}
			}
			if (in != null) {
				try {
					in.close();
				} catch (Exception e) {
					// //Log.println(Log.ERROR, AppDefines.NRANGE_TAG,
					// e.toString());
				}
			}

		}
		return null;

	}

}
